#include <thread>
#include <chrono>
#include "mysqlConnect.h"
#include "mqttClient.h"
#include "unistd.h"
#include <regex>
#include <nlohmann/json.hpp>
using json = nlohmann::json;




int main() {
    MysqlConnect sqlclient;
    sqlclient.ConnectInit();
    // 这里的mysql和顺序不能换
    MqttClient client("testClient", "127.0.0.1", 1883);


    client.setMessageSubscription([&](){
        client.subscribeTopic("smartfarm/+/sensor/data");
        client.subscribeTopic("smartfarm/+/controller/status");
        client.subscribeTopic("smartfarm/+/constantValue/data");
        client.subscribeTopic("smartfarm/+/controller/cmd");
        client.subscribeTopic("smartfarm/+/setConstantValue/cmd");
        client.subscribeTopic("smartfarm/+/getConstantValue/cmd");
        client.subscribeTopic("smartfarm/+/user/status");
        // std::cout << "订阅结束" << std::endl;
        // client.publishMessage("smartfarm/1/controller/status", "", 0, true);
        // client.publishMessage("smartfarm/2/controller/status", "", 0, true);
        // client.publishMessage("smartfarm/3/controller/status", "", 0, true);
    });

    client.setMessageCallback([&](const std::string& topic, const std::string& message){
        std::cout << "收到消息: " << topic << " => " << message << std::endl;

        try {
            json data = json::parse(message);

            // 客户端日志
            if(topic == "smartfarm/+/setConstantValue/cmd"){
                // mysqlClient.insertUserStatus(data["username"], data["status"], data["time_stamp"]);
                std::cout << "smartfarm/1/setConstantValue/cmd" << std::endl;
                return;
            }

            // 1. 传感器数据
            std::regex sensorRegex(R"(smartfarm/(\d+)/sensor/data)");
            std::smatch match;
            if(std::regex_match(topic, match, sensorRegex)){
                int farm_id = std::stoi(match[1]);
                if (!sqlclient.farmIsExist(farm_id)) return;
                if(sqlclient.insertSensorData(farm_id, data["co2"], data["temperature"], data["humidity"], data["light_intensity"], data["time_stamp"]) != 0){
                    std::cout << "插入失败" << std::endl;
                }
                return;
            }

            // 2. 仓库中控状态
            std::regex ctrlRegex(R"(smartfarm/(\d+)/controller/status)");
            if(std::regex_match(topic, match, ctrlRegex)){
                int farm_id = std::stoi(match[1]);
                if (!sqlclient.farmIsExist(farm_id)) return;
            
                if(data["status"] == "on"){
                    std::cout << farm_id << "上线啦" << std::endl;
                    if(sqlclient.exec("UPDATE farm_info SET state=1 WHERE farm_id="+ std::to_string(farm_id)) != 0){
                        std::cout << "更新状态失败" << std::endl;
                    }
                }else if(data["status"] == "off"){
                    std::cout << farm_id << "下线啦" << std::endl;
                    if(sqlclient.exec("UPDATE farm_info SET state=0 WHERE farm_id="+ std::to_string(farm_id)) != 0){
                        std::cout << "更新状态失败" << std::endl;
                    }
                }
                return;
            }

            // 3. 获取到的恒定值
            std::regex constRegex(R"(smartfarm/(\d+)/constantValue/data)");
            if(std::regex_match(topic, match, constRegex)){
                int farm_id = std::stoi(match[1]);
                
                if (!sqlclient.farmIsExist(farm_id)) return;
                sqlclient.exec("SELECT * FROM farm_info WHERE farm_id=" + std::to_string(farm_id));
                if(sqlclient.resultCount() == 0)
                    return;
                return;
            }

            // 4. 仓库中控状态
            std::regex uesrRegex(R"(smartfarm/(.*)/user/status)");
            if(std::regex_match(topic, match, uesrRegex)){
                std::string userId = match[1];
            
                if(data["status"] == "on"){
                    std::cout << "用户：\"" << userId << " \"上线啦" << std::endl;
                }else if(data["status"] == "off"){
                    std::cout << "用户："<< userId << "下线啦" << std::endl;
                }
                return;
            }



            // // 5. 农场上下线日志
            // std::regex statusRegex(R"(smartfarm/(\d+)/controler/status)");
            // if(std::regex_match(topic, match, constRegex)){
            //     int farm_id = std::stoi(match[1]);
            //     // mysqlClient.insertConstantValue(farm_id, data["co2"], data["temperature"], data["humidity"], data["light_intensity"], data["time_stamp"]);
            //     return;
            // }
        } catch(const std::exception& e){
            std::cerr << "解析错误: " << e.what() << std::endl;
        }
    });

    while (true)
    {
        sleep(1);
    }
    

    // 析构时会自动 disconnect + loop_stop
    return 0;
}
